package com.jijia.webbase.filter;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jijia.webbase.config.response.JsonResult;
import com.jijia.webbase.domain.User;
import com.jijia.webbase.utils.SpringContextUtil;
import com.jijia.webbase.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;


@Component
@Slf4j
public class UserNameAndPassWordFilter extends OncePerRequestFilter {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//        获取请求url
        String url = request.getRequestURI();
        HashMap<String, Object> threadLocal = new HashMap<>();
        log.debug("UserNameAndPassWordFilter过滤器中 url: {}", url);
        if (url.startsWith("/login")) {
//            获取请求体
//             获取请求体（通过 getInputStream）
            StringBuilder stringBuilder = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
            }

            String body = stringBuilder.toString();
            User user = JSONUtil.toBean(body, User.class);
            log.debug("请求体: {}", user);

            Authentication authentication = null;
            try {
                AuthenticationManager authenticationManager = SpringContextUtil.getBean(AuthenticationManager.class);
                log.debug("Attempting to authenticate user: {}", user.getUserName());
                authentication = authenticationManager.authenticate(
                        new UsernamePasswordAuthenticationToken(
                                user.getUserName(),
                                user.getUserPassword()
                        )
                );
                SecurityContextHolder.getContext().setAuthentication(authentication);
                threadLocal.put("validationLoginStatus", true);
                ThreadLocalUtil.set(threadLocal);
                log.debug("login 认证结果: {}", authentication);
            } catch (LockedException e) {
                threadLocal.put("validationLoginStatus", false);
                ThreadLocalUtil.set(threadLocal);
//                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置 HTTP 状态码为 401 Unauthorized
//                response.setContentType("application/json;charset=UTF-8");  // 设置响应的字符编码为 UTF-8
//                response.getWriter().write("{\"message\": \"账户被锁定！！\"}"); // 返回错误信息
//                return;
            } catch (Exception e) {
                threadLocal.put("validationLoginStatus", false);
                ThreadLocalUtil.set(threadLocal);
//                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置 HTTP 状态码为 401 Unauthorized
//                response.setContentType("application/json;charset=UTF-8");  // 设置响应的字符编码为 UTF-8
//                response.getWriter().write("{\"message\": \"认证失败！\"}"); // 返回错误信息
//                return;
            }


        }
        //             调用 filterChain.doFilter 确保请求继续向下执行
        filterChain.doFilter(request, response);
    }
}
